package com.yusp75.myexam.di

import androidx.room.Room
import androidx.room.migration.Migration
import androidx.sqlite.db.SimpleSQLiteQuery
import androidx.sqlite.db.SupportSQLiteDatabase
import com.yusp75.myexam.com.yusp75.myexam.data.BookRepository
import com.yusp75.myexam.com.yusp75.myexam.data.BrowsePagingSource
import com.yusp75.myexam.com.yusp75.myexam.data.QuestionRepository
import com.yusp75.myexam.com.yusp75.myexam.data.ResultOfAnswer
import com.yusp75.myexam.com.yusp75.myexam.di.PrefManager
import com.yusp75.myexam.data.ExamDatabase
import com.yusp75.myexam.data.ExcelToRoomHelper
import com.yusp75.myexam.data.InMemoryDatabase
import com.yusp75.myexam.data.LearningStrategy
import com.yusp75.myexam.ui.books.BookViewModel
import com.yusp75.myexam.ui.browse.BrowseViewModel
import com.yusp75.myexam.ui.display.DisplayViewModel
import com.yusp75.myexam.ui.exam.ExamResultViewModel
import com.yusp75.myexam.ui.home.HomeViewModel
import com.yusp75.myexam.ui.setting.SettingViewModel
import kotlinx.coroutines.Dispatchers
import org.koin.android.ext.koin.androidContext
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.core.qualifier.named
import org.koin.dsl.module

val appModule = module {

    // 持久化数据库实例(单例)
    single {
        Room.databaseBuilder(
            androidContext(),
            ExamDatabase::class.java,
            "my_exam.db"
        ).addMigrations(MIGRATION_1_2) // 包含视图创建的迁移
            .build()
    }

    // 内存数据库实例(单例)
    single {
        Room.databaseBuilder(
            androidContext(),
            InMemoryDatabase::class.java,
            "im_exam.db"
        ).build()
    }

    single { get<ExamDatabase>().bookDao() }
    single { get<ExamDatabase>().questionDao() }
    single { get<ExamDatabase>().recordDao() }

    // scope data
    single { DataHolder() }

    single {
        ExcelToRoomHelper(
            bookDao = get(),
            questionDao = get()
        )
    }

    val pagingModule = module {

        factory { (query: SimpleSQLiteQuery) ->
            BrowsePagingSource(
                questionDao = get(),
                query = query
            )
        }
    }


    single { PrefManager(get()) }
    single { LearningStrategy(questionDao = get(), recordDao = get()) }

    // ViewModel的注入声明
    // viewModel { HomeViewModel(get(), get()) }
    // 第一个get()对应bookDao，第二个对应questionDao
    viewModel {
        HomeViewModel(
            bookDao = get(),
            questionDao = get(),
            recordDao = get(),
            prefManager = get(),
            holder = get()
        )

    }
    viewModel {
        DisplayViewModel(
            recordDao = get(),
            prefManager = get(),
            holder = get(),
            repository = get()
        )
    }

    viewModel {
        BrowseViewModel(
            questionDao = get(),
            exerciseRecordDao = get(),
            holder = get(),
            prefManager = get(),
            repository = get()
        )
    }

    viewModel {
        ExamResultViewModel(
            repository = get(),
            holder = get()
        )
    }

    // 书籍
    viewModel { BookViewModel(get(), get()) }

    // 设置
    viewModel { SettingViewModel(get(), get()) }

    // 内存数据库
    // 考试结果
    single { get<InMemoryDatabase>().examResultDao() }
    //
}

// scope share
class DataHolder {
    var bookId: Int = 0 // 存储共享的bookId
    var totalQuestionNum: Int = 0 //
    var choiceQuestionNum: Int = 0
    var judgeQuestionNum: Int = 0
    var questionNum: Int = 0 // 题目数量
    var totalTimeElapsed: Long = 0  // 做题耗费时间
    lateinit var resultOfAnswers: List<ResultOfAnswer>
}

val sessionModule = module {
    scope(named("DataSession")) {
        scoped { DataHolder() } // 数据持有类
    }
}

// 仓库模块
val repositoryModule = module {
    single {
        QuestionRepository(
            questionDao = get(),
            ioDispatcher = Dispatchers.IO
        )
    }

    single { BookRepository(get()) }

}

object MIGRATION_1_2 : Migration(1, 2) {
    override fun migrate(database: SupportSQLiteDatabase) {
        database.execSQL(
            """
            CREATE VIEW IF NOT EXISTS QuestionStatsView AS
            SELECT 
                q.id AS questionId,
                ROUND(AVG(CASE WHEN a.isCorrect = 1 THEN 1.0 ELSE 0.0 END), 2) AS correctRate,
                ROUND(AVG(CASE WHEN a.hesitationTime > 3000 THEN 1.0 ELSE 0.0 END), 2) AS hesitateRate
            FROM questions q
            LEFT JOIN answer_records a ON q.id = a.questionId
            GROUP BY q.id
        """
        )

        // 可选：添加索引提升视图查询性能
        database.execSQL(
            """
            CREATE INDEX IF NOT EXISTS idx_answer_records_question 
            ON answer_records(questionId)
        """
        )
    }
}